#include "mainwindow.h"
#include "ui_mainwindow.h"

void MainWindow::intUI()
{
    label = new QLabel;
    label -> setMidLineWidth(150);
    label -> setText("字数：0");
    ui->statusBar->addWidget(label);

    spinbox = new QSpinBox;
    spinbox->setValue(30);                                      //字体大小栏初始值为15
    ui -> mainToolBar -> addWidget(new QLabel("字体大小"));
    ui -> mainToolBar -> addWidget(spinbox);
    ui->textEdit->setFontPointSize(30);                         //字体大小初始尺寸15

    fontcombobox = new QFontComboBox;
    ui -> mainToolBar -> addWidget(new QLabel("字体"));
    ui -> mainToolBar -> addWidget(fontcombobox);

    searchwindow = new SearchWindow;
    searchwindow -> setWindowTitle("查找和替换");                //设置搜索框名

    time = new QTimer(this);
    time -> start(500);
}

void MainWindow::connect_set()
{
    connect(spinbox,SIGNAL(valueChanged(int)),                  //on_控件名_信号名字默认是隐式connect，再写connect会产生冲突
            this,SLOT(spinBoxFontSize_valueChanged(int)));

    connect(fontcombobox,SIGNAL(currentIndexChanged(const QString&)),
            this,SLOT(comboFont_currentIndexChanged(const QString&)));

    connect(searchwindow, &SearchWindow::find_signal, this, &MainWindow::compare_and_locate);   //更新

    connect(searchwindow, &SearchWindow::replace_signal, this, &MainWindow::replace);   //替换

    connect(time, &QTimer::timeout, this, &MainWindow::update_count_text);  //每隔一段时间更新一次count_text
}

MainWindow::MainWindow(QWidget *parent) :   //MainWindow类的构造函数
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    intUI();
    connect_set();
    setCentralWidget(ui->textEdit);
}

MainWindow::~MainWindow()   //MainWindow类的析构函数
{
    //searchwindow -> close();  //????????????????????????????????????????????????????
    delete ui;
}

void MainWindow::on_actioncuti_triggered(bool checked)  //设置文本为粗体
{
    QTextCharFormat fff;
    fff=ui->textEdit->currentCharFormat();
    if(checked)
    {
        fff.setFontWeight(QFont::Bold);
    }
    else
    {
        fff.setFontWeight(QFont::Normal);
    }
    ui ->textEdit->mergeCurrentCharFormat(fff);
}

void MainWindow::spinBoxFontSize_valueChanged(int aFontSize)  //设置文本字体大小
{
    QTextCharFormat fff;
    fff.setFontPointSize(aFontSize);
    ui ->textEdit ->mergeCurrentCharFormat(fff);
}

void MainWindow::comboFont_currentIndexChanged(const QString &argl) //设置文本字体
{
    QTextCharFormat fff;
    fff.setFontFamily(argl);
    ui->textEdit->mergeCurrentCharFormat(fff);
}


void MainWindow::on_actionxieti_triggered(bool checked) //设置文本为斜体
{
    QTextCharFormat fff;
    fff=ui->textEdit->currentCharFormat();
    if(checked)
    {
        fff.setFontItalic(QFont::Bold);
    }
    else
    {
        fff.setFontItalic(QFont::StyleNormal);
    }
    ui ->textEdit->mergeCurrentCharFormat(fff);
}

void MainWindow::on_actionxiahuaxian_triggered(bool checked)    //为文本增添下划线
{
    QTextCharFormat fff;
    fff=ui->textEdit->currentCharFormat();
    if(checked)
    {
        fff.setFontUnderline(QFont::Bold);
    }
    else
    {
        fff.setFontUnderline(QFont::StyleNormal);
    }
    ui ->textEdit->mergeCurrentCharFormat(fff);
}

void MainWindow::on_actionxinjian_triggered()   //新建文件
{
    MainWindow * newTable = new MainWindow;
       newTable->show();
}

void MainWindow::on_actiondakai_triggered() //打开文件
{
    QString curpath=QDir::currentPath();//保存当前路径
    QString dlgTitle="打开一个文件";
    QString filter="程序文件(*.h *.cpp);;文本文件(*.txt);;所有文件(*.*)";
    QString afilname=QFileDialog::getOpenFileName(this,dlgTitle,curpath,filter);
     if(afilname.isEmpty())
      {
          return;
      }
      openStreamText(afilname);
}

bool MainWindow::openStreamText(const QString afilname) //
{
    QFile aFile(afilname);

    if(!aFile.exists())//如果文件不存在
        return false;

    if(!aFile.open(QIODevice::ReadOnly |QIODevice::Text))//如果不是以只读和文本方式打开文件返回false
        return false;


    QTextStream aStream(&aFile);//文本流读取文件
    aStream.setCodec("UTF-8");
    aStream.setAutoDetectUnicode(true);//自动检测unicode便于显示汉字
    ui->textEdit->setPlainText(aStream.readAll());

    aFile.close();

    return true;
}

void MainWindow::on_actionbaocun_triggered()    //保存文件
{
    QString e= ui->textEdit->toPlainText();
        QFile file;
        file.setFileName(QFileDialog::getSaveFileName(this,QString("保存路径"),QString("/"),QString("TEXT(*.txt)")));
        file.open(QIODevice::WriteOnly | QIODevice::Text);
        file.write(e.toUtf8());
        file.close();
}

void MainWindow::on_actionyanse_2_triggered()   //设置文本颜色
{
    QColor color = QColorDialog::getColor(Qt::red,this);
        if(color.isValid())
        {
            QTextCharFormat fmt;
            fmt.setForeground(color);
            ui->textEdit->mergeCurrentCharFormat(fmt);
        }
}

void MainWindow::on_actionyouduiqi_triggered()  //设置文本右对齐
{
    ui->textEdit->setAlignment(Qt::AlignRight);
}


void MainWindow::on_actionzuoduiqi_triggered()  //设置文本左对齐
{
    ui->textEdit->setAlignment(Qt::AlignLeft);
}

void MainWindow::on_actionjuzhongduiqi_triggered()  //设置文本中间对齐
{
    ui->textEdit->setAlignment(Qt::AlignCenter);
}

void MainWindow::on_actionsousuohetihuan_triggered()    //打开搜索框
{
    searchwindow->show();
}

void MainWindow::update_count_text()
{
    count_text = ui -> textEdit -> toPlainText().size();
    label -> setText("字数：" + QString::number(count_text));
}

void MainWindow::compare_and_locate(bool option)
{
    QString findtext = searchwindow -> getFindText();
    //if (ui -> textEdit -> find(findtext, QTextDocument::FindBackward) == false)
    //{
       // QMessageBox::information(this, "注意", "未找到查找内容", QMessageBox::Ok);
      //  return;
    //}
    //ui -> textEdit -> moveCursor(QTextCursor::Start);
    bool ok;
    if (option == 0)
        ok = ui -> textEdit -> find(findtext, QTextDocument::FindBackward);
    else
        ok = ui -> textEdit -> find(findtext);
    if (ok)
    {
        QPalette palette = ui -> textEdit -> palette();
        palette.setColor(QPalette::Text, QColor(180, 180, 180));
        ui -> textEdit -> setPalette(palette);
    }
    else
    {
        ui -> textEdit -> moveCursor(QTextCursor::Start);
    }
}

void MainWindow::replace(const QString to_find, const QString to_replace)
{
    QTextCursor cursor = ui -> textEdit -> textCursor();
    if (cursor.hasSelection() && cursor.selectedText() == to_find)
    {
        cursor.removeSelectedText();
        cursor.insertText(to_replace);
    }
}

void MainWindow::on_actiontupian_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this,
                                    "选择图片",
                                    ".",
                                    "JPEG(*.jpg *.jpeg);;"
                                    "GIF(*.gif);;"
                                    "PNG(*.png)");
       QUrl url(QString("file:%1").arg(fileName));
       QImage image = QImageReader(fileName).read();
       //在文档中添加图片
       ui->textEdit->document()->addResource(QTextDocument::ImageResource,
                                             url, QVariant(image));
       QTextCursor cursor = ui->textEdit->textCursor();
       QTextImageFormat imgFormat;
       imgFormat.setName(url.toString());      //获取文件路径
       imgFormat.setWidth(image.width());      //设置图片宽
       imgFormat.setHeight(image.height());    //设置图片高
       cursor.insertImage(image);              //在光标处插入图片
}

void MainWindow::on_actionbiaoge_triggered()
{
    QTextCursor cursor = ui->textEdit->textCursor();
    QTextTableFormat format;    	//表格格式
    format.setCellSpacing(15);
    format.setCellPadding(20);
    cursor.insertTable(3,4,format); //在光标处插入3行4列的表格
}
